<!-- 台本文件夹页面——未使用！！ -->
<template>
  <ele-modal
    width="600px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="this.data && this.data.id ? '编辑台本' : '新建台本'"
    :limit="30"
    @update:visible="updateVisible"
  >
    <el-upload
      v-if="data && !data.id || accept"
      :show-file-list="false"
      style="margin-right: 10px"
      :action="ossUrl"
      accept=".srt"
      :on-change="uploadClick"
      multiple
      :limit="1"
      :file-list="fileList"

    >
      <el-button
        type="primary"
        size="small"
        class="ele-btn-icon e-btn-bottom"
        icon="el-icon-folder-add"
      >
        导入SRT解析
      </el-button>
    </el-upload>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
      style="max-width: 700px; margin: 10px auto;position: relative;"
    >
      <el-form-item label="台本名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入台本名称" class="e-input" :disabled="disabled" />
      </el-form-item>
      <ul class="infinite-list" style="overflow:auto; height: 400px;">
<!--        status:(已创建）0-1：转换中 2：转换完成-->
        <el-row>
          <el-col v-if="accept ||data&&data.status==2">
            <div v-for="(item, index) in form.list" :key="index">
              <!--校检表单-->
              <el-form-item :label="'台词'+(index+1)" :prop="'list.'+index+'.content'" :rules="rules.contents">
                <div style="display:flex;">
                <el-input v-model="item.content" placeholder="请输入台词" class="e-input" @input="changeMney(item,index)" style="width: 388px" />
                <!--加减-->
                <div v-if="disabled!=true">
                <el-button class="btn-position" @click="add" v-if="0==index" >+</el-button>
                <!--<el-button class="btn-position" @click="add" v-if="form.list.length-1==index" >+</el-button>-->
                <el-button class="btn-position" @click="subtract(index)" v-else >-</el-button></div>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col v-else>
            <el-form-item :label="'台词'">
              <el-input placeholder="台词转换中,请稍等……" class="e-input" :disabled="true" /></el-form-item>
          </el-col>
        </el-row>
      </ul>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save" :disabled="!accept && !data || !accept && data.status!=2">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import axios from 'axios'
  import {getToken} from "../../../../utils/token-util";
  import { resolveSRT,saveText,updateText } from '@/api/creatCenter/material';
  export default {
    name: "file-text",
    data() {
      const defaultForm = {
        title:'',
        list:[{
          content:''
        }]
      };
      return {
        disabled:false,
        dialogTableVisible: false,
        fileList: [],
        // 提交状态
        loading: false,
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          contents: [
            { required: true,
              message: '请输入台词',
              trigger: 'blur' }
          ],
          title: [
            {
              required: true,
              message: '请输入台本名称',
              trigger: 'blur'
            }
          ]
        },
      }
    },
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 父级 id
        parentId: Number,
        //accept存在代表是新建台本
        accept:String,
        // 文件数据
        data: Object
      },
      methods:{
        //上传事件
        uploadClick(file){

          console.log("11111111111")
          this.fileList.push(file)
          console.log('this.fileList',this.fileList,this.fileList.length);
          //非上传到阿里云的，都需要转换为表单传值
          let formdata = new FormData()
          formdata.append('file', this.fileList[0].raw,this.fileList[0].name)
          //token 白名单
          let token = getToken()
          let config = {
            headers: {
              'Authorization': token
            }
          }
          //, config 白名单
          axios.post('http://localhost/business/montage/srt/resolveSRT', formdata).then(res => {
            console.log(res)
            console.log('res.data',res.data)
            let data=res.data.data
            this.form.list.push(...data);
            console.log("this.form.list",this.form.list)
            this.fileList=[]
          })
        },
        changeMney(data,index){
          console.log("进入修改=========")
          this.form.list[index].content=data.content;
          let arr=[];  //新数组
          this.form.list.forEach(item=>{
            arr.push(item);
          })
          this.form.list=arr;//相当于返回一个新数组可以触发渲染
          console.log('this.form.list2222',this.form.list)

        },
        //  加
        add(){
          let content={content:''}
          this.form.list.push(content)
          console.log('this.form.list',this.form.list,this.form.list.length)
        },
        //减
        subtract(index){
          this.form.list.splice(index, 1)
          console.log("this.form.list",this.form.list,this.form.list.length)
        },
        /* 保存编辑 */
        save() {
          console.log('11', this.form)

          this.$refs.form.validate((valid) => {
            if (!valid) {
              return false;
            }
            this.loading = true;
            let list= JSON.stringify( this.form.list );
            let isTrue=this.data&&this.data.mediaId?this.data.mediaId:''
            let mediaId=  this.data&&this.data.mediaId?this.data.mediaId:''
            let scriptType=isTrue?2:1;
            //键值id 存在（弹框） 或者 “新建台本”
            if(this.form.id || this.parentId){
              saveText({
                scriptName:this.form.title+'.txt',  //台本名称
                scriptType:scriptType ,     //台本类型  1文字台本2口播台本
                mediaId:mediaId,   //媒资id 口播台本时需传递
                folderId:this.parentId,  //所属文件夹ID
                content:list,   //台本内容  json数组字符串
                username: this.$store.state.user.info.username
              })
                .then((data) => {
                  this.loading = false;
                  console.log("成功", data)
                  this.$message.success('新建台本成功！');
                  this.updateVisible(false);
                  this.$emit('done');
                })
                .catch((e) => {
                  console.log("失败e", e)
                  this.loading = false;
                  this.$message.error(e);
                });
            }
            else{
              let ids=this.data && this.data.id?this.data.id:''
              updateText({
                scriptName:this.form.title+'.txt',  //台本名称
                content:list,   //台本内容  json数组字符串
                id:ids   //台本主键
              })
                .then((msg) => {
                  this.loading = false;
                  console.log("成功", msg)
                  this.$message.success(msg);
                  this.updateVisible(false);
                  this.$emit('done');
                })
                .catch((e) => {
                  console.log("失败e", e)
                  this.loading = false;
                  this.$message.error(e);
                });
            }


          });
        },
        /* 更新 visible */
        updateVisible(value) {
          console.log('this.accept',this.accept)
          this.$emit('update:visible', value);
        },
      },

    created(){
      console.log('data',this.data,'form',this.form);
  },
    watch: {
      visible(visible) {
        console.log("visible==============",visible,'this.data',this.data)
        if (!visible) {
          this.$refs.form.clearValidate();
          this.form= { ...this.defaultForm }
          this.form.list[0].content=''
        }
        else{
          if (this.data) {
            console.log("JSON.parse(this.data.content)",JSON.parse(this.data.content),'this.data',this.data,this.data.scriptName)
            //json字符串转数组
            this.$set(this.form,'title',this.data.scriptName)
            // this.form.title=this.data.scriptName;
            //有媒资id则禁用，否则可以修改
            this.disabled=this.data.mediaId?true:false
            if (this.data.content) {
              this.form.list = JSON.parse(this.data.content);
            }
            console.log('转换后的json台本=======',this.form.list,'this.disabled',this.disabled)
          }
        }
      }
    }
    }
</script>

<style scoped>

  .e-btn-bottom {
   margin-bottom: 10px;
  }
  .text {
    font-size: 14px;
  }

  .item {
    padding: 18px 0;
  }

  .box-card {
    width: 480px;
  }
  .e-input{
    width: 388px;
    margin-right: 15px;
  }
  .btn-position{
    /*position: absolute;bottom: 0;*/
    right: 10px;
  }
</style>
